# -*- coding: utf-8 -*-
from flask import *
from flask_cors import CORS, cross_origin
from sql_mehods import *
import warnings
import requests
import os
import subprocess
from werkzeug.utils import secure_filename
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import tika
from tika import parser
import uuid
import PyPDF2
from docx.enum.table import WD_ALIGN_VERTICAL

warnings.filterwarnings("ignore", category=FutureWarning)
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
db = MySQLHelper(host='106.53.97.117', port=3307,
                 user='newuser', password='password',
                 db='sys', charset='utf8')
app = Flask(__name__, static_url_path="/static")
# 应用程序初始化配置跨域访问策略
cors = CORS(app, resources={r"/*": {"origins": "*"}})


# 用户注册API
@app.route('/register',
           methods=['POST'])
@cross_origin()
def register():
    # 从请求JSON中获取用户名和密码
    username = request.get_json()['username']
    password = request.get_json()['password']
    import datetime
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    sql = "INSERT INTO admin (name, password,score,status,suo,scorea,scoreb,times,emial) VALUES ('{}', '{}','0','1','个人号',12,3,'{}','0')".format(
        username, password, current_time)
    db.execute_select(sql)

    return jsonify({"status": "success", "message": 1})


# 登录API
@app.route('/login', methods=['POST'])
@cross_origin()
def login():
    # 从请求JSON中获取用户名和密码
    username = request.get_json()['username']
    password = request.get_json()['password']
    # 在客户表中查找匹配的数据
    sql = "SELECT * FROM admin WHERE name='{}' AND password='{}' AND status!='0'".format(username, password)
    result = db.execute_select(sql)

    # 检查是否有匹配的数据
    if len(result) > 0:
        return jsonify({"status": "success", "message": "登录成功"})
    else:
        return jsonify({"status": "fail", "message": "登录失败，请检查用户名和密码"})


@app.route('/uploadimg', methods=['POST'])
@cross_origin()
def uploadimg():
    file = request.files['file']
    filename = request.args.get("filename")
    pdf_file_path = str(filename)
    # 保存上传的文件
    filename = pdf_file_path
    file_path = os.path.join('./static/images', filename + '.jpg')
    file.save(file_path)
    # 调用之前的函数进行文件解析
    return jsonify({"data": "上传成功！"})


# 自定义查询数据
@app.route('/sql')
@cross_origin()
def select():
    db = MySQLHelper(host='106.53.97.117', port=3307,
                     user='newuser', password='password',
                     db='sys', charset='utf8')
    sql = request.args.get('sql', '')
    data = db.execute_select(sql)
    return jsonify({"data": data})


@app.route('/ups', methods=["POST"])
@cross_origin()
def ups():
    # 设置随机数，进行随机登录：
    sql = request.get_json()['sql']
    # 检查用户名是否已存在
    data = db.execute_select(sql)
    return jsonify({"data": data})


@app.route('/ups2', methods=["POST"])
@cross_origin()
def ups2():
    # 设置随机数，进行随机登录：
    sql = request.get_json()['sql']
    # db1 = MySQLHelpe
    # 检查用户名是否已存在
    data = db.execute_select(sql)
    return jsonify({"data": data})


@app.route('/sqls')
@cross_origin()
def sqls():
    # 设置随机数，进行随机登录：
    # 设置随机数，进行随机登录：
    # sql = request.get_json()['sql']
    sql = request.args.get('sqls', '')
    # 检查用户名是否已存在
    data = db.execute_select(sql)
    return jsonify({"data": data})


import base64


# 运行编辑器
# latex识别
def image_to_base64(image_path):
    with open(image_path, 'rb') as image_file:
        encoded_string = base64.b64encode(image_file.read())
    return encoded_string.decode('utf-8')


@app.route('/generate/<username>', methods=['GET'])
def generate(username):
    image_name = f'./static/{username}'
    base64_string = image_to_base64(image_name)

    url = 'https://open.ocrmath.com/v3/printed/ocr'
    headers = {
        'app_key': '892653',
        'app_secret': '48195c4871faaf5b72a08d7872bf2179'
    }
    data = {
        'base64': base64_string
    }

    response = requests.post(url, headers=headers, data=data)
    print(response)

    return jsonify({'latex': response.json()['data']['latex']})


@app.route('/upload', methods=['POST'])
@cross_origin()
def upload_file():
    file = request.files['file']
    filename = request.args.get("filename")
    pdf_file_path = str(filename)
    # 保存上传的文件
    filename = pdf_file_path
    file_path = os.path.join('./static', filename)
    file.save(file_path)
    # 调用之前的函数进行文件解析
    return jsonify({"data": "上传成功！"})


# 赛题
@app.route('/upfile', methods=['POST'])
@cross_origin()
def upload_fils():
    file = request.files['file']
    filename = request.args.get("filename")
    pdf_file_path = str(filename) + ".pdf"
    # 保存上传的文件
    file_path = os.path.join('./static', pdf_file_path)
    file.save(file_path)
    # 调用之前的函数进行文件解析
    return jsonify({"data": "上传成功！"})


# 数据
@app.route('/updata', methods=['POST'])
@cross_origin()
def updata():
    file = request.files['file']
    pdf_file_path = request.args.get("filename")
    # 保存上传的文件
    filename = str(pdf_file_path) + ".csv"
    file_path = os.path.join('./static', filename)
    file.save(file_path)
    # 调用之前的函数进行文件解析
    return jsonify({"data": "上传成功！"})


@app.route('/images/<path:filename>')
def get_image(filename):
    return send_from_directory('static/emp', filename)


# 生成tex
@app.route('/genertex', methods=['POST'])
@cross_origin()
def genertex():
    data = request.get_json()
    text = data['text']
    id = data['id']
    filename = id + '.tex'
    with open(os.path.join(BASE_DIR, 'static', filename), 'w') as f:
        f.write(text)
    return {"message": "tex file created successfully"}


# 生成docx
@app.route('/generdoc', methods=['POST'])
@cross_origin()
def generdoc():
    data = request.get_json()
    id = data['id']
    tex_filename = os.path.join(BASE_DIR, 'static', f"{id}.tex")
    docx_filename = os.path.join(BASE_DIR, 'static', f"{id}.docx")
    command = f"pandoc {tex_filename} --reference-doc=template.docx -o {docx_filename}"
    try:
        subprocess.run(command, shell=True, check=True)
        return {"message": "docx file created successfully"}
    except subprocess.CalledProcessError as e:
        return {"message": f"Command execution failed: {str(e)}"}


# 下载docx

from flask import send_from_directory


@app.route('/downloaddoc/<id>', methods=['GET'])
@cross_origin()
def downloaddoc(id):
    return id


# 生成md
@app.route('/mgenertex', methods=['POST'])
@cross_origin()
def mgenertex():
    data = request.get_json()
    text = data['text']
    id = data['id']
    try:
        filename = 'm' + id + '.tex'
        with open(os.path.join(BASE_DIR, 'static', filename), 'w') as f:
            f.write(text)
        filename = 'm' + id + '.md'
        with open(os.path.join(BASE_DIR, 'static', filename), 'w') as f:
            f.write(text)
        return {"message": "tex file created successfully"}

    except:
        filename = 'm' + id + '.md'
        with open(os.path.join(BASE_DIR, 'static', filename), 'w') as f:
            f.write(text)
        return {"message": "md file created successfully"}


# 生成mdocx
@app.route('/mgenerdoc', methods=['POST'])
@cross_origin()
def mgenerdoc():
    data = request.get_json()
    id = data['id']
    profile = "Md"
    tex_filename = os.path.join(BASE_DIR, 'static', f"m{id}.md")
    docx_filename = os.path.join(BASE_DIR, 'static', f"m{id}.docx")
    command = f"pandoc {tex_filename} --reference-doc=template.docx -o {docx_filename}"
    try:
        subprocess.run(command, shell=True, check=True)
        return {"message": "docx file created successfully",
                "file_path": "http://106.53.97.117:2088/static/" + docx_filename, "status": profile}
    except subprocess.CalledProcessError as e:
        return {"message": f"Command execution failed: {str(e)}"}


# 生成但是不下载 提供url地址 进行改写初始脚本
# 生成mdocx
from docx2pdf import convert
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import requests
from io import BytesIO
from docx import Document
from docx.shared import Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx2pdf import convert
from docx.shared import RGBColor
from docx.shared import Pt
from flask import request
import re
import subprocess
# 也需要同事转化为图片一份 而且是指定名
@app.route('/convertdoc', methods=['POST'])
@cross_origin()
def convertdoc():
    data = request.get_json()
    mathid = data['id']
    text = data['text']
    # pythonngradesn
    # 如果识别目前是属于闪现表  则 进行进入特定的端口请求
    data1 = str(text).split("符号说明")

    if len(data1)>1:
        matches = re.search(r'\{[\s\S]*?\}', text)
        if matches:
            # 提取匹配内容中的所有行
            extracted_text = matches.group(0)
            extracted_text = extracted_text
            print(extracted_text,"测试结果")
            # 去除花括号
            extracted_text = extracted_text.strip('{}')

            # 使用正则表达式分割列表项
            items = re.findall(r'\[.*?\]', extracted_text)

            # 将字符串转换为列表
            list_representation = [eval(item) for item in items]

            # 打印结果
            print(list_representation)
        else:
            list_representation=[]
        grades = list_representation
        def set_vertical_cell_alignment(cell, align="bottom"):
            try:
                align_values = {
                    "top": WD_ALIGN_VERTICAL.TOP,
                    "center": WD_ALIGN_VERTICAL.CENTER,
                    "bottom": WD_ALIGN_VERTICAL.BOTTOM
                }
                cell.vertical_alignment = align_values[align]
            except KeyError:
                raise ValueError("Invalid vertical alignment: {}".format(align))
        def Set_cell_border(cell: _Cell, **kwargs):
            """
            设置单元格边框函数
            使用方法:
            Set_cell_border(
                cell,
                top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                bottom={"sz": 12, "color": "#00FF00", "val": "single"},
                start={"sz": 24, "val": "dashed", "shadow": "true"},
                end={"sz": 12, "val": "dashed"},
            )
            传入参数有cell, 即单元格；top指上边框；bottom指下边框；start指左边框；end指右边框。
            "sz"指线的粗细程度；"val"指线型，比如单线，虚线等；"color"指颜色，颜色编码可百度；
            "space"指间隔，一般不设置，设置的值大于0会导致线错开；"shadow"指边框阴影
            """
            tc = cell._tc
            tcPr = tc.get_or_add_tcPr()

            tcBorders = tcPr.first_child_found_in("w:tcBorders")
            if tcBorders is None:
                tcBorders = OxmlElement('w:tcBorders')
                tcPr.append(tcBorders)

            for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
                edge_data = kwargs.get(edge)
                if edge_data:
                    tag = 'w:{}'.format(edge)

                    element = tcBorders.find(qn(tag))
                    if element is None:
                        element = OxmlElement(tag)
                        tcBorders.append(element)

                    for key in ["sz", "val", "color", "space", "shadow"]:
                        if key in edge_data:
                            element.set(qn('w:{}'.format(key)), str(edge_data[key]))

        # 如果存在符号说明：
        head_table_dict = ['符号', '符号含义', '单位']
        data_table_dict = grades
        print(data_table_dict,"测试结果")
        document = Document()
        table = document.add_table(1, len(head_table_dict), style='Normal Table')
        heading_cells = table.rows[0].cells
        for k in range(len(heading_cells)):
            heading_cells[k].text = head_table_dict[k]
            # 将该单元格的垂直对齐设为底对齐
            set_vertical_cell_alignment(heading_cells[k], "center")
            Set_cell_border(
                heading_cells[k],
                top={"sz": 15, "color": "#000000", "val": "single"},
                bottom={"sz": 10, "color": "#000000", "val": "single"},
                # end={"sz": 6, "color": "#000000", "val": "single"}
            )
        cells = ""
        for data in data_table_dict:
            cells = table.add_row().cells
            for value_index in range(len(data)):
                cells[value_index].text = data[value_index]

        for k in range(0, len(heading_cells)):
            Set_cell_border(
                cells[len(cells) - k - 1],
                bottom={"sz": 12, "color": "#000000", "val": "single"},
            )

            paragraph = heading_cells[k].paragraphs[0]
            p_pr = paragraph._element.get_or_add_pPr()
            spacing = OxmlElement('w:spacing')
            spacing.set(qn('w:before'), str(Pt(0.01)))  # 例如在段落前面增加6磅的间距
            p_pr.insert(0, spacing)
        # 标志上表格的中间表
        p = document.add_paragraph()
        p_content = p.add_run(f"""表1.符号说明表""")  # 前面空格为4个，表示缩进4个空格
        p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        p_content.font.name = 'Arial'  # 设置字体为Arial
        p_content._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 设置中文字体为宋体

        document.save(f'./static/m{mathid}.docx')
    else:
        try:
            profile = "Tex"
            tex_filename = os.path.join(BASE_DIR, 'static', f"m{mathid}.md")
            docx_filename = os.path.join(BASE_DIR, 'static', f"m{mathid}.docx")
            command = f"pandoc {tex_filename} --reference-doc=template.docx -o {docx_filename}"
            subprocess.run(command, shell=True, check=True)
        except:
            profile = "Md"
            tex_filename = os.path.join(BASE_DIR, 'static', f"m{mathid}.md")
            docx_filename = os.path.join(BASE_DIR, 'static', f"m{mathid}.docx")
            command = f"pandoc {tex_filename} --reference-doc=template.docx -o {docx_filename}"
            subprocess.run(command, shell=True, check=True)
        url = f'http://106.53.97.117:2088/static/m{mathid}.docx'
        response = requests.get(url)
        if response.status_code == 200:
            # 读取响应内容作为二进制流
            file_stream = BytesIO(response.content)
            # 使用python-docx库加载文档
            doc = Document(file_stream)
        else:
            doc = Document()

        # 设置全文样式
        style = doc.styles['Normal']
        font = style.font
        font.name = 'Times New Roman'
        font.size = Pt(12)
        paragraph_format = style.paragraph_format
        paragraph_format.line_spacing = 2.0  # 1.5倍行距

        def bold_terms_in_braces(paragraph):
            new_runs = []  # 新runs列表
            in_braces = False  # 是否位于大括号内部
            temp_text = ""  # 用于储存临时文本
            for run in paragraph.runs:
                # 遍历run中的每个字符
                for char in run.text:
                    if char == '{':  # 开始大括号
                        if temp_text:  # 如果之前有文本，先添加到new_runs中
                            new_runs.append((temp_text, False))
                            temp_text = ""  # 清空临时文本
                        in_braces = True  # 设置位于大括号内部标志为True
                    elif char == '}':  # 结束大括号
                        if temp_text:  # 如果大括号内有文本，加粗后添加到new_runs中
                            new_runs.append((temp_text, True))
                            temp_text = ""
                        in_braces = False  # 设置位于大括号内部标志为False
                    else:  # 普通字符
                        temp_text += char  # 添加到临时文本
                if temp_text:  # 在完成一个run后，将剩余文本添加到new_runs中，根据in_braces判断是否加粗
                    new_runs.append((temp_text, in_braces))
                    temp_text = ""

            # 删除原段落的runs
            for run in paragraph.runs:
                run.clear()

            # 根据new_runs中的内容和格式创建新的runs
            for text, is_bold in new_runs:
                new_run = paragraph.add_run(text)
                new_run.bold = is_bold

        # 遍历段落并应用加粗及去除大括号功能
        for paragraph in doc.paragraphs:
            if '关键词' in paragraph.text or '拟题' in paragraph.text:
                bold_terms_in_braces(paragraph)
                for run in paragraph.runs:
                    run.font.bold = True
                    run.font.name = '黑体'
            elif paragraph.text.startswith('摘要') or paragraph.text.startswith('摘 要') or paragraph.text.startswith('问题分析') \
                    or paragraph.text.startswith('{模型假设设}') or paragraph.text.startswith('{模型建立与求解}'):
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                run = paragraph.runs[0]
                run.font.bold = True
                run.font.name = '黑体'
                run.font.size = Pt(16)  # 假设摘要标题字号大小为16
            else:
                bold_terms_in_braces(paragraph)
        # 保存更改
        doc.save(docx_filename)
        # output_path = f'math{mathid}.pdf'

    # 采用 fitz 尝试把 pdf转化为对应的图片
    import fitz
    def fitzz_pdf_to_covernt_img(pdf_path, file_name):
        pdf_document = fitz.open(pdf_path)
        for page_number in range(len(pdf_document)):
                print(f"-----------------------正在转换中...-----------------")
                # 获取页面
                page = pdf_document[page_number]

                # 渲染页面为图像 - 可选参数设置分辨率，这里设置为300 DPI.
                pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))

                # 设置输出图片文件名
                output_image_path = f"./static/{file_name}{page_number+1}.png"

                # 将渲染的页面保存为PNG格式的图片
                pix.save(output_image_path)
        pdf_document.close()
    file_name =  f"m{mathid}.pdf"



    # 构建 unoconv 转换命令
    pdf_path = os.path.join('./static', f"m{mathid}.pdf")
    docx_path = os.path.join('./static', f"m{mathid}.docx")
    command = ["unoconv", "-f", "pdf", "-o", pdf_path, docx_path]
    # 使用sudo执行命令
    try:
        subprocess.check_call(command, preexec_fn=os.setuid(0))
    except subprocess.CalledProcessError as e:
        print(f"Error converting file: {e}")
    # except subprocess.CalledProcessError as e:
    #     print(f'An error occurred while converting m{mathid}.docx to PDF with unoconv: {e}')
    try:
        fitzz_pdf_to_covernt_img(f"./static/{file_name}", file_name.split(".")[0])
        print(f'Converted m{mathid}.docx to m{mathid}.pdf successfully with unoconv.')
        return {"msg": f'm{mathid}.pdf', "status": profile,"img_url": f"m{mathid}.png"}
    except Exception as e:
        print(e)
        return {"error": str(e)}

# 生成md
@app.route('/hgenertex', methods=['POST'])
@cross_origin()
def hgenertex():
    data = request.get_json()
    text = data['text']
    id = data['id']
    filename = 'h' + id + '.html'
    with open(os.path.join(BASE_DIR, 'static', filename), 'w') as f:
        f.write(text)
    return {"message": "tex file created successfully"}


# 生成mdocx
@app.route('/hgenerdoc', methods=['POST'])
@cross_origin()
def hgenerdoc():
    data = request.get_json()
    id = data['id']
    tex_filename = os.path.join(BASE_DIR, 'static', f"h{id}.html")
    docx_filename = os.path.join(BASE_DIR, 'static', f"h{id}.docx")
    command = f"pandoc {tex_filename} --reference-doc=template.docx -o {docx_filename}"
    try:
        subprocess.run(command, shell=True, check=True)
        return {"message": "docx file created successfully"}
    except subprocess.CalledProcessError as e:
        return {"message": f"Command execution failed: {str(e)}"}


# 上传的固定文件取名格式：+ "." + str(file.filename.split(".")[-1])
@app.route('/uploads', methods=['POST'])
@cross_origin()
def upload_files():
    # 如果上传的是docx 则顺便转化为对应的pdf文件
    def docx_convert_pdf(docx_path, pdf_path):
        def extract_and_save_first_five_paragraphs(input_docx_filename):
            doc = Document(input_docx_filename)
            new_doc = Document()

            for i, paragraph in enumerate(doc.paragraphs):
                if i >= 150:  # 只提取前5个段落
                    break
                new_doc.add_paragraph(paragraph.text)

            new_doc.save(input_docx_filename)
        # 假设你的原始docx文件名为"example.docx"，输出文件名为"first_five_paragraphs.docx"
        output_docx_filename = extract_and_save_first_five_paragraphs(docx_path)
        # 使用 subprocess.call 来正确调用 unoconv 命令
        subprocess.call(["unoconv", "-f", "pdf", "-o", pdf_path, docx_path])
    def split_pdf(input_pdf_path, output_folder):
        # 打开PDF文件读取器
        pdf_reader = PyPDF2.PdfReader(input_pdf_path)
        num_pages = len(pdf_reader.pages)
        latex_adr_list = []
        basurl = "http://106.53.97.117:2088/static/"
        # 遍历所有页面并且分别保存为单个PDF
        for page in range(num_pages):
            pdf_writer = PyPDF2.PdfWriter()  # 创建一个PDF写入器
            pdf_writer.add_page(pdf_reader.pages[page])  # 将当前页面添加到写入器
            latex_adr = str(uuid.uuid4())

            # 定义输出的PDF文件名
            output_filename = f"./static/{latex_adr}.pdf"

            # 写入单个页面的PDF
            with open(output_filename, 'wb') as output_pdf:
                pdf_writer.write(output_pdf)
            latex_adr_list.append(basurl + latex_adr + ".pdf")

        return latex_adr_list

    file = request.files['file']
    filename = request.args.get("filename")
    username = request.args.get("username")
    print(username)
    # 查询对应的用户id
    sql = f"select ids from admin where name = '{username}'"
    data = db.execute_select(sql)
    user_id = data[0]['ids']
    pdf_file_path = str(uuid.uuid4()) +"."+ str(file.filename.split(".")[-1])
    url_path = f'http://106.53.97.117:2088/static/{pdf_file_path}'
    update_sql = f"""INSERT INTO maxstudio_files_table (file_adr, file_content,file_thems_type, file_type, file_length, name_ids)
    VALUES (
      '{url_path}',
        '{filename}',
      '{filename}',
      'document',
      1000, -- 假定的文字数，请根据实际PDF文档的文字数替换此值
      {user_id} -- 假定的上传者编号，与用户信息表关联的ID
    );
    """
    try:
        data = db.execute_edit(update_sql)
    except:
        update_sql = f"""INSERT INTO maxstudio_files_table (file_adr, file_content,file_thems_type, file_type, file_length, name_ids)
        VALUES (
          '{url_path}',
            '{filename}',
          '{filename}',
          'document',
          1000, -- 假定的文字数，请根据实际PDF文档的文字数替换此值
          10001 -- 假定的上传者编号，与用户信息表关联的ID
        );
        """
        data = db.execute_edit(update_sql)
    # 保存上传的文件
    filename = pdf_file_path
    file_path = os.path.join('./static', filename)
    file.save(file_path)
    # 如果是 docx 则进行转换处理：
    pdf_url_list = []
    if filename.split(".")[1] =='docx':
        pdf_url_list=[]
        # pdf_path = os.path.join('./static', filename.split(".docx")[0] + ".pdf")
        # docx_convert_pdf(file_path,pdf_path)
        # pdf_url_list = split_pdf(pdf_path, "./static")
    elif filename.split(".")[1] =='doc':
        try:
            pdf_path = os.path.join('./static', filename.split(".doc")[0] + ".pdf")
            docx_convert_pdf(file_path,pdf_path)
            pdf_url_list = split_pdf(pdf_path, "./static")
        except Exception as e:
            print(e)
            pdf_url_list=[]
    elif filename.split(".")[1] =='pdf':
        try:
            pdf_url_list = split_pdf(file_path,"./static")
        except Exception as e:
            print(e)
    # 再次返回  能否分割的地址 以及存储  分割的
    return {
        "pdf":pdf_file_path,
        "pdf_list":pdf_url_list
    }


@app.route('/parse', methods=['POST'])
@cross_origin()
def parse_file():
    username = request.get_json()['username']
    sql = f"select ids from admin where name = '{username}'"
    data = db.execute_select(sql)
    user_id = data[0]['ids']
    file_path = request.get_json()["file_path"]
    if file_path:
        file_path = os.path.join('./static', file_path)
        if os.path.exists(file_path):
            parsed = parser.from_file(file_path)['content']
            print(parsed)
            # 对这份数据进行分类
            url="http://106.53.97.117:7777/v1/api-g4model"
            headers={'Content-Type':'application/json'}
            data={
                "input_text":f"根据这些文本，我需要你给我返回一个类别（如果包含很多数据应该返回'数学建模数据') (你可以在这里选['数学建模赛题','数学建模数据','文学','IT','情感','办公','其它','数据'])，请不要有其它输出！:{parsed}"
            }
            response=requests.post(url,headers=headers,json=data)
            if response.status_code == 200:
                print("请求成功！")
                # 处理返回的数据
                print(response.json().get('result'))  # 假设 API 返回的是 JSON 格式的数据
            else:
                print("请求失败，错误码：", response.status_code)
            # 存储内容
            try:
                sql = f"""update maxstudio_files_table set file_content ='{parsed}' , file_type="{response.json().get('result')}" where name_ids ={user_id}"""
                print(sql,"hhh")
                db.execute_edit(sql)
                return jsonify({"text_content": parsed})
            except Exception as e:
                sql = f"""update maxstudio_files_table set file_content ='{parsed}' , file_type=`{response.json().get('result')}` where name_ids ={user_id}"""
                return jsonify({"text_content": sql})
        else:
            return "File not found", 404
    else:
        return "File path not provided", 400


from pymongo import MongoClient
from bson.json_util import dumps


@app.route("/items", methods=["GET"])
def read_items():
    client = MongoClient("mongodb://zengweijia:zwj798261@106.53.97.117:27018")
    db1 = client['admin']
    items_cursor = db1['model_helplist'].find()
    items = [item for item in items_cursor]  # Iterate through the cursor to get all the items
    json_data = dumps(items)  # Convert to JSON format
    return jsonify(json.loads(json_data))  # Return as JSON response


# 新增 deploy 接口  了解接口需求  编写接口
# 以请求后端数据库数据为例
@app.route("/deploydata", methods=["GET"])
def deploydata():
    sql = f"""select * from deployprojects"""
    data = db.execute_select(sql)
    return jsonify(data)


# 自动化部署执行   写个flask接口
# autodeploy.sh  restart_flask.sh    运行的地址的
#   /home/lighthouse/autodeployment/autodeploy.sh
#   /home/lighthouse/autodeployment/restart_flask.sh
# 这是脚本地址  传入是 自动化运行的文件  然后运行这个脚本  返回  项目已经运行

# 自动化运行脚本
@app.route("/rundeploy", methods=["GET"])
def rundeploy():
    script = request.args.get('script')

    try:
        subprocess.call([f"/home/lighthouse/studiomianserver/{script}.sh"])
        return jsonify({"message": "项目已经运行"})
    except:
        return jsonify({"message": "发布失败"}), 404


@app.route('/sendemail', methods=['GET'])
def send_email():
    # 获取通过query string传入的email地址
    email = request.args.get('email')
    if not email:
        return jsonify(success=False, message="No email provided"), 400

    mail_host = 'smtp.qq.com'
    mail_user = '3146838460@qq.com'
    mail_pass = 'vfaexsbkiuqidhaf'
    sender = '3146838460@qq.com'
    receivers = [email]  # 使用从请求中获取的邮箱地址作为接收者

    msg = MIMEMultipart()
    msg['Subject'] = '中国大学生CUAEU数学探索联盟会'
    msg['From'] = "{}".format(sender)
    msg['To'] = ",".join(receivers)
    html_content = """
    <p style="color:black;">欢迎来到maxstudio！<br>
    <br>分享即可获得：<br>
    分享一个好友注册成功可获取：<br>
    ③20次/GPT4数模神器<br>
    ④100次/公式识别</p>
    """
    msg.attach(MIMEText(html_content, 'html', 'utf-8'))

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, msg.as_string())  # 发送
        smtpObj.quit()  # 关闭连接
        return jsonify({"success": "True"})
    except smtplib.SMTPException as e:
        return jsonify({"success": "False"})





@app.route('/map_msg_pdf_list',methods=['POST'])
def map_msg_pdf_list():
    import os
    import fitz
    def fitzz_pdf_to_covernt_img(pdf_path, file_name):
        pdf_document = fitz.open(pdf_path)
        for page_number in range(len(pdf_document)):
            if (len(pdf_document) > 1):
                pass
            else:
                print(f"-----------------------正在转换中...-----------------")
                # 获取页面
                page = pdf_document[page_number]

                # 渲染页面为图像 - 可选参数设置分辨率，这里设置为300 DPI.
                pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))

                # 设置输出图片文件名
                output_image_path = f"./static/{file_name}.png"

                # 将渲染的页面保存为PNG格式的图片
                pix.save(output_image_path)
        pdf_document.close()
    map_msg_pdf_list = request.get_json()['map_msg_pdf_list']
    for file_name in map_msg_pdf_list:
        if file_name.split(".")[1] == "pdf":
            try:
                fitzz_pdf_to_covernt_img(f"./static/{file_name}", file_name.split(".")[0])
            except Exception as e:
                print(f"出问题了{e}")
    return {"status":"转换成功",
            "img_url_list":[]}

@app.route('/yuque/webhook', methods=['POST'])
def respond():
    emisql = f"""select name from admin
 where name like '%@%'"""
    emildist = db.execute_charts(emisql)
    for k in emildist['name']:
        print(k)
        try:
            import time
            # 从内层的 'data' 中获取 body_html 和 name 字段的内容
            try:
                inner_data = request.json.get('data', {})
                body_html = inner_data.get('body_html', '')
                name = "UP大大"
            except:
                inner_data = "自主服务测试中，请勿回复"
                body_html = "自主服务测试中，请勿回复"
                name = "UP大大"

            # QQ邮箱服务器地址
            mail_host = 'smtp.qq.com'
            # QQ邮箱用户名(即QQ邮箱地址)
            mail_user = '3146838460@qq.com'
            # QQ邮箱密码(这里应填写授权码，而非登录密码)
            mail_pass = 'vfaexsbkiuqidhaf'

            sender = '3146838460@qq.com'
            receivers = ['3780382169@qq.com', 'Peterliang071224@gmail.com', 'sadddddddd.@gmail.com']  # 接收邮件的邮箱地址

            # 创建一个带附件的实例2397730704@qq.com
            msg = MIMEMultipart()

            # 邮件主题
            msg['Subject'] = 'CUAEU数学探索联盟会'
            msg['From'] = "{}".format(sender)
            msg['To'] = ",".join(receivers)

            # 邮件正文内容
            html_content = f"<html><body>{body_html}<br>Posted by: {name}</body></html>"

            msg.attach(MIMEText(html_content, 'html', 'utf-8'))

            try:
                smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
                smtpObj.login(mail_user, mail_pass)  # 登录验证
                smtpObj.sendmail(sender, receivers, msg.as_string())  # 发送
                print("Mail has been sent successfully.")
            except smtplib.SMTPException as e:
                print(e)
            print("发送成功")
            time.sleep(60)
        except:
            pass

    return jsonify({"data": request.json})


import platform

if __name__ == "__main__":
    # 生产模式
    if platform.system() == 'Linux':
        app.run(host='10.0.12.11', port=2088)
    else:
        app.run()
